var access_token = sessionStorage.getItem("access_token");
var referer = location.href;

if (access_token == null || access_token == '') {
	login();
} else {
	$.ajax({
		url: 'http://localhost:8880/user/me',
		headers: {
			'Authorization': 'bearer ' + access_token
		},
		error: function(data) {
			login();
		}
	})
}

$('#logout').click(function() {
	$.ajax({
		url: 'http://localhost:8881/logout',
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		}
	});
	$.ajax({
		url: 'http://localhost:8882/logout',
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		}
	});
	sessionStorage.removeItem("access_token");
	sessionStorage.removeItem("username");
	sessionStorage.removeItem("nickname");
	location.href = "http://localhost:8880/logout?referer=" + referer+"&access_token="+access_token;
})

function login() {
	location.href = "http://localhost:8880/oauth/authorize?" +
		"client_id=webapp&" +
		"redirect_uri=http://localhost:8848/demo/callback.html&" +
		"response_type=code&" +
		"state=" + referer;
}
